<template>
  <div class="register-form-wrapper">
    <div class="register-form-title">{{ $t("register.form.title") }}</div>
    <div class="register-form-sub-title">{{ $t("register.form.title") }}</div>
    <div class="register-form-error-msg">{{ errorMessage }}</div>
    <a-form ref="registerForm" :model="userInfo" class="login-form" layout="vertical" @finish="handleSubmit">
      <a-form-item
        name="username"
        :rules="[
          { required: true, message: $t('register.form.userName.errMsg'), trigger: 'blur' },
          { type: 'email', message: $t('register.form.userName.email.errMsg'), trigger: 'blur' }
        ]"
      >
        <a-input v-model:value="userInfo.username" :placeholder="$t('register.form.userName.placeholder')">
          <template #prefix>
            <UserOutlined style="color: rgb(78, 89, 105); margin-right: 12px" />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        name="password"
        :rules="[
          { required: true, message: $t('register.form.password.errMsg'), trigger: 'blur' },
          { min: 6, max: 16, message: $t('register.form.password.length.errMsg'), trigger: 'blur' }
        ]"
      >
        <a-input-password v-model:value="userInfo.password" :placeholder="$t('register.form.password.placeholder')" allow-clear>
          <template #prefix>
            <LockOutlined style="color: rgb(78, 89, 105); margin-right: 12px" />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item name="rePassword" :rules="[{ validator: validateRepassword, trigger: 'blur' }]">
        <a-input-password
          v-model:value="userInfo.rePassword"
          :placeholder="$t('register.form.rePassword.placeholder')"
          allow-clear
        >
          <template #prefix>
            <LockOutlined style="color: rgb(78, 89, 105); margin-right: 12px" />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item name="captcha" :rules="[{ validator: validateCaptcha, trigger: 'blur' }]">
        <a-space>
          <a-input v-model:value="userInfo.captcha" :placeholder="$t('register.form.captcha.placeholder')" allow-clear>
            <template #prefix>
              <MailOutlined style="color: rgb(78, 89, 105); margin-right: 12px" />
            </template>
          </a-input>
          <a-button class="send-email-btn" @click="handleSendCaptcha">{{ captchaButtonText }}</a-button>
        </a-space>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <a-button type="primary" html-type="submit" block :loading="loading">
          {{ $t("register.form.register") }}
        </a-button>
        <a-button type="text" block class="register-form-register-btn" @click="handleBack">
          {{ $t("register.form.back") }}
        </a-button>
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from "vue"
import { useI18n } from "vue-i18n"
import useLoading from "@/hooks/loading"
import { useUserStore } from "@/store"
import { OperationType, RegisterData, sendCaptcha } from "@/api/user"
import { Rule } from "ant-design-vue/es/form"
import { message } from "ant-design-vue"
import { UserOutlined, LockOutlined, MailOutlined } from "@ant-design/icons-vue"

const emits = defineEmits(["login"])
const { t } = useI18n()
const errorMessage = ref("")
const { loading, setLoading } = useLoading()

const userInfo = reactive({
  username: "",
  password: "",
  rePassword: "",
  captcha: ""
})

const validateRepassword = (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject(t("register.form.rePassword.errMsg"))
  }
  if (value !== userInfo.password) {
    return Promise.reject(t("register.form.rePassword.errMsg"))
  } else {
    return Promise.resolve()
  }
}
const validateCaptcha = (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject(t("register.form.captcha.errMsg"))
  }
  const re = /\d{6}/
  if (!re.test(value)) {
    return Promise.reject(t("register.form.captcha.format.errMsg"))
  }
  return Promise.resolve()
}
const userStore = useUserStore()
const handleSubmit = async (values: any) => {
  if (loading.value) return
  setLoading(true)
  try {
    await userStore.register(values as RegisterData)
    message.success(t("register.form.register.success"))
    setTimeout(() => {
      emits("login")
    }, 1500)
    countDown.value = 0
  } catch (err) {
    errorMessage.value = (err as Error).message
  } finally {
    setLoading(false)
  }
}

const registerForm = ref()
let countDown = ref(0)
const EXPIRES_TIME = 15 * 60 //验证码有效时间
let captchaButtonText = computed(() => {
  if (countDown.value == 0) return t("register.form.send.captcha")
  return countDown.value + "s"
})
const handleSendCaptcha = () => {
  if (countDown.value != 0) return
  registerForm.value.validate(["username"]).then(() => {
    sendCaptcha({
      email: userInfo.username,
      operationType: OperationType.register
    }).then(() => {
      countDown.value = EXPIRES_TIME
      updataCountdown()
      message.success(t("register.form.send.captcha.success"))
    })
  })
}
const updataCountdown = () => {
  const timer = setInterval(() => {
    if (countDown.value > 0) {
      countDown.value--
    } else {
      clearInterval(timer)
    }
  }, 1000)
}

const handleBack = () => {
  emits("login")
}
</script>
<style lang="scss" scoped>
.register-form {
  &-wrapper {
    width: 320px;
  }

  &-title {
    font-size: 24px;
    color: #1d2129;
    font-weight: 500;
    line-height: 32px;
  }

  &-sub-title {
    font-size: 16px;
    color: #86909c;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: #f53f3f;
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &-register-btn {
    color: #86909c !important;
  }
  :deep(.ant-input-affix-wrapper) {
    background-color: #f2f3f5;
    border: none;
    color: #1d2129;
    border-radius: 0;
    height: 32px;
    input {
      background-color: #f2f3f5;
    }
  }
}
:deep(.send-email-btn) {
  border-radius: 0;
  font-size: 12px;
}
</style>
